/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
qui(
    function(require, exports, module) {

        Ancestor.Dao = (function() {
            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);